package controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import domain.Alternative;
import domain.AlternativePair;
import domain.Criteria;
import domain.CriteriaPair;
import domain.Project;
import domain.ProjectPair;

/**
 * Servlet implementation class PreferenceController
 */
public class PreferenceController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PreferenceController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String requestUri = request.getRequestURI();
		if (requestUri != null && requestUri.endsWith("/preference")){
			String criteriaId = request.getParameter("criteriaId");
			Criteria criteria = null;
			String projectId = request.getParameter("projectId");
			Project project = null;
			try {
				project = Project.find(Long.parseLong(projectId));
				project.findAlternatives();
				
				criteria = Criteria.find(Long.parseLong(criteriaId));
				criteria.findSubCriterias();
//				criteria.findComparison();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			request.setAttribute("criteria", criteria);
			request.setAttribute("alternatives", project.getAlternatives());
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/preference.jsp");
			dispatcher.forward(request,response);
		}else if(requestUri != null && requestUri.endsWith("/preferenceGoal")){
			String id = request.getParameter("projectId");
			Project project = null;
			try {
				project = Project.find(Long.parseLong(id));
				project.findCriterias();
				project.findAlternatives();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			request.setAttribute("project", project);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/preferenceGoal.jsp");
			dispatcher.forward(request,response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String requestUri = request.getRequestURI();
		if (requestUri != null && requestUri.endsWith("/preference")){
			String message = "";
			String criteriaId = request.getParameter("criteriaId");
			String type = request.getParameter("type");
			String [] subjects = request.getParameterValues("subject");
			String [] objects = request.getParameterValues("object");
			String [] scores = request.getParameterValues("score");
			String [] preferences = request.getParameterValues("preference");
			
			Criteria criteria = null;
			Project project = null;
			try {
				
				criteria = Criteria.find(Long.parseLong(criteriaId));
				if(type.equals("criteria")){
					for(int i=0; i<subjects.length; i++){
						CriteriaPair comparison = new CriteriaPair();
							comparison.setCriteria(criteria);
							if(preferences[i].equals(subjects[i]))
								comparison.setScore(Double.parseDouble(scores[i]));
							else{
								double inverseVal = 1.0/Double.parseDouble(scores[i]);
								comparison.setScore(inverseVal);
							}
							comparison.setSubject(Criteria.find(Long.parseLong(subjects[i])));
							comparison.setObject(Criteria.find(Long.parseLong(objects[i])));
							comparison.setType(type);
						comparison.insert();
					}
				}else if(type.equals("alternative")){
					for(int i=0; i<subjects.length; i++){
						AlternativePair comparison = new AlternativePair();
							comparison.setCriteria(criteria);
							if(preferences[i].equals(subjects[i]))
								comparison.setScore(Double.parseDouble(scores[i]));
							else{
								double inverseVal = 1.0/Double.parseDouble(scores[i]);
								comparison.setScore(inverseVal);
							}
							comparison.setSubject(Alternative.find(Long.parseLong(subjects[i])));
							comparison.setObject(Alternative.find(Long.parseLong(objects[i])));
							comparison.setType(type);
						comparison.insert();
					}
				}
				
				criteria.findProject();
				// Create new Vector for it
				criteria.findSubCriterias();
				criteria.findComparison();
				criteria.createVector();
				
				project = criteria.getProject();
				project.findAlternatives();
				project.findCriterias();
				project.findComparison();
				message = "Preference was successfully created";
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			request.setAttribute("project", project);
			request.setAttribute("message", message);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/project.jsp");
			dispatcher.forward(request,response);
		}else if(requestUri != null && requestUri.endsWith("/preferenceGoal")){
			String message = "";
			String projectId = request.getParameter("projectId");
			String type = request.getParameter("type");
			String [] subjects = request.getParameterValues("subject");
			String [] objects = request.getParameterValues("object");
			String [] scores = request.getParameterValues("score");
			String [] preferences = request.getParameterValues("preference");
			
			Project project = null;
			try {
				
				project = Project.find(Long.parseLong(projectId));
				for(int i=0; i<subjects.length; i++){
					ProjectPair comparison = new ProjectPair();
						comparison.setProject(project);
						if(preferences[i].equals(subjects[i]))
							comparison.setScore(Double.parseDouble(scores[i]));
						else{
							double inverseVal = 1.0/Double.parseDouble(scores[i]);
							comparison.setScore(inverseVal);
						}
						comparison.setSubject(Criteria.find(Long.parseLong(subjects[i])));
						comparison.setObject(Criteria.find(Long.parseLong(objects[i])));
						comparison.setType(type);
					comparison.insert();
				}
				
				project.findAlternatives();
				project.findCriterias();
				project.findComparison();
				// Create new Vector for it
				project.createVector();
				project.findCriterias();// refresh priority 
				message = "Preference was successfully created";
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			request.setAttribute("project", project);
			request.setAttribute("message", message);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/project.jsp");
			dispatcher.forward(request,response);
		}
	}

}
